using System;
using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;

namespace NUnitForVSTS.NUnitTest
{
    /// <summary>
    /// Generates Hash Id's for the Unit Tests.
    /// Apparently these are not just guids, these are SHA1 hashes of the test cases.
    /// http://blogs.msdn.com/dhopton/archive/2008/06/12/helpful-internals-of-trx-and-vsmdi-files.aspx
    /// </summary>
	static class HashUtility
	{
        /// <summary>
        /// Has provider to generate Guid
        /// Preloads the provider with the sha1 hash provider
        /// </summary>
		private static HashAlgorithm provider = new SHA1CryptoServiceProvider();

        /// 
        /// Calculates a hash of the string and copies the first 128 bits of the hash
        /// to a new Guid.
        ///<param name="data">Data to generate guid from</param>
		internal static Guid GuidFromString(string data)
		{
            Check.NotNull(data, "data");
            byte[] hash = provider.ComputeHash(System.Text.Encoding.Unicode.GetBytes(data));

            // Guid is always 16 bytes
            Debug.Assert(Guid.Empty.ToByteArray().Length == 16, "Expected Guid to be 16 bytes");

            byte[] toGuid = new byte[16];
            Array.Copy(hash, toGuid, 16);

            return new Guid(toGuid);
		}
	}
}